package org.dxy.trigger.http;

import com.alibaba.fastjson.JSON;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dxy.api.dto.request.ThreadPoolConfigRequest;
import org.dxy.api.dto.vo.ThreadPoolConfigViewVo;
import org.dxy.middleware.dynamic.thread.pool.application.view.ThreadPoolView;
import org.dxy.middleware.dynamic.thread.pool.domain.command.RefreshThreadPoolConfigCommand;
import org.dxy.middleware.dynamic.thread.pool.domain.model.ThreadPoolAggregate;
import org.dxy.middleware.dynamic.thread.pool.trigger.sdk.ThreadPoolConfigSDK;
import org.redisson.api.RTopic;
import org.redisson.api.RedissonClient;
import org.springframework.web.bind.annotation.*;
import org.dxy.api.dto.response.R;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @ description:
 * @ author: dxy
 * @ createTime: 2025/10/2 18:14
 */
@Slf4j
@RestController
@RequestMapping("/api/v1/dynamic/thread/pool/")
@RequiredArgsConstructor
public class DynamicThreadPoolController {
   private final ThreadPoolConfigSDK threadPoolConfigCommandSDK;
    @Resource
    public RedissonClient redissonClient;

    /**
     * 查询线程池数据
     * curl --request GET \
     * --url 'http://localhost:8089/api/v1/dynamic/thread/pool/query_thread_pool_list'
     */
    @GetMapping( "query_thread_pool_list")
    public R<List<ThreadPoolConfigViewVo>> queryThreadPoolList() {
        try {
            List<ThreadPoolView> threadPoolViewList = threadPoolConfigCommandSDK.getThreadPoolViewList();
            // 转换为视图对象
            List<ThreadPoolConfigViewVo> viewList = threadPoolViewList.stream()
                    .map(threadPoolView -> ThreadPoolConfigViewVo.builder()
                            .appName(threadPoolView.getAppName())
                            .threadPoolName(threadPoolView.getThreadPoolName())
                            .corePoolSize(threadPoolView.getCorePoolSize())
                            .maximumPoolSize(threadPoolView.getMaximumPoolSize())
                            .activeCount(threadPoolView.getActiveCount())
                            .poolSize(threadPoolView.getPoolSize())
                            .queueType(threadPoolView.getQueueType())
                            .queueSize(threadPoolView.getQueueSize())
                            .remainingCapacity(threadPoolView.getRemainingCapacity())
                            .build())
                    .toList();
            return R.ok(viewList);
        } catch (Exception e) {
            log.error("查询线程池数据异常", e);
            return R.fail();

        }
    }

    /**
     * 查询线程池配置
     * curl --request GET \
     * --url 'http://localhost:8089/api/v1/dynamic/thread/pool/query_thread_pool_config?appName=dynamic-thread-pool-test-app&threadPoolName=threadPoolExecutor'
     */
    @RequestMapping(value = "query_thread_pool_config", method = RequestMethod.GET)
    public R<ThreadPoolConfigViewVo> queryThreadPoolConfig(@RequestParam String appName, @RequestParam String threadPoolName) {
        try {
            ThreadPoolView threadPoolView = threadPoolConfigCommandSDK.getThreadPoolView(appName,threadPoolName);
            ThreadPoolConfigViewVo threadPoolConfigViewVo = ThreadPoolConfigViewVo.builder()
                    .appName(threadPoolView.getAppName())
                    .threadPoolName(threadPoolView.getThreadPoolName())
                    .corePoolSize(threadPoolView.getCorePoolSize())
                    .maximumPoolSize(threadPoolView.getMaximumPoolSize())
                    .activeCount(threadPoolView.getActiveCount())
                    .poolSize(threadPoolView.getPoolSize())
                    .queueType(threadPoolView.getQueueType())
                    .queueSize(threadPoolView.getQueueSize())
                    .remainingCapacity(threadPoolView.getRemainingCapacity())
                    .build();
            return R.ok(threadPoolConfigViewVo);
        } catch (Exception e) {
            log.error("查询线程池配置异常", e);
            return R.fail();
        }
    }

    /**
     * 修改线程池配置
     * curl --request POST \
     * --url http://localhost:8089/api/v1/dynamic/thread/pool/update_thread_pool_config \
     * --header 'content-type: application/json' \
     * --data '{
     * "appName":"dynamic-thread-pool-test-app",
     * "threadPoolName": "threadPoolExecutor",
     * "corePoolSize": 1,
     * "maximumPoolSize": 10
     * }'
     */
    @RequestMapping(value = "update_thread_pool_config", method = RequestMethod.POST)
    public R<Void> updateThreadPoolConfig(@RequestBody ThreadPoolConfigRequest request) {
        try {
            log.info("修改线程池配置开始 {} {} {}", request.getAppName(), request.getThreadPoolName(), JSON.toJSONString(request));
            RefreshThreadPoolConfigCommand command = RefreshThreadPoolConfigCommand.builder()
                    .appName(request.getAppName())
                    .threadPoolName(request.getThreadPoolName())
                    .corePoolSize(request.getCorePoolSize())
                    .maximumPoolSize(request.getMaximumPoolSize())
                    .build();
            threadPoolConfigCommandSDK.refresh(command);
            log.info("修改线程池配置完成 {} {}", request.getAppName(), request.getThreadPoolName());


//            log.info("修改线程池配置开始 {} {} {}", request.getAppName(), request.getThreadPoolName(), JSON.toJSONString(request));
//            RTopic topic = redissonClient.getTopic("DYNAMIC_THREAD_POOL_REDIS_TOPIC" + "_" + request.getAppName());
//            topic.publish(request);
//            log.info("修改线程池配置完成 {} {}", request.getAppName(), request.getThreadPoolName());
            return R.ok();
        } catch (Exception e) {
            log.error("修改线程池配置异常 {}", JSON.toJSONString(request), e);
            return R.fail();
        }
    }
}
